package com.ruoyi.app.controller;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.JSONObjectPro;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.AppPage;
import com.ruoyi.common.utils.SnowFlakeIDGenerator;
import com.ruoyi.gwc.domain.TApprovalApply;
import com.ruoyi.gwc.domain.TDispatchVehicles;
import com.ruoyi.gwc.domain.TVehicleApplication;
import com.ruoyi.gwc.service.ITApprovalApplyService;
import com.ruoyi.gwc.service.ITDispatchVehiclesService;
import com.ruoyi.gwc.service.ITVehicleApplicationService;
import com.ruoyi.system.domain.DriverInfo;
import com.ruoyi.system.domain.VehicleManagement;
import com.ruoyi.system.service.IDriverInfoService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.IVehicleManagementService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用车申请模块
 */
@RestController
@RequestMapping("/app/vehicleApplication")
@Slf4j
public class AppVehicleApplicationController extends BaseController {

    @Autowired
    private ITVehicleApplicationService tVehicleApplicationService;
    @Autowired
    private ITDispatchVehiclesService itDispatchVehiclesService;
    @Autowired
    private ITApprovalApplyService itApprovalApplyService;
    @Autowired
    private IDriverInfoService driverInfoService;
    @Autowired
    private IVehicleManagementService vehicleManagementService;
    @Autowired
    private ISysDeptService deptService;

    @ApiOperation("查看所有用车申请单分页")
    @GetMapping("/vehicleApplyList")
    public AjaxResult vehicleApplyList(@RequestParam(value = "orderStatus", required = false ) Long orderStatus,
                                       @RequestParam(value = "companyId", required = false ) Long companyId,
                                       @RequestParam Integer pageNum, @RequestParam Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        LoginUser loginUser = getLoginUser();
        TVehicleApplication tVehicleApplication = new TVehicleApplication();
        if(loginUser.getUser().getUserType() == 1 ) {//用户类型（0系统用户，1移动端用户，2驾驶员，3管理员）
            tVehicleApplication.setApplyTel(loginUser.getUser().getPhonenumber());
            //订单状态（0：已申请，1：已审批，2已调度，3已接单，4已出车，5已还车，6撤销订单）
            tVehicleApplication.setOrderStatus(orderStatus);
        }else if (loginUser.getUser().getUserType() == 2){
            tVehicleApplication.setDriverId(loginUser.getUser().getUserId());
            tVehicleApplication.setDispatchOrderStatus(orderStatus);
        }else {
            //订单状态（0：已申请，1：已审批，2已调度，3已接单，4已出车，5已还车，6撤销订单）
            tVehicleApplication.setOrderStatus(orderStatus);
        }

        if (companyId == null){
            companyId = loginUser.getDeptId();
        }
        tVehicleApplication.setCompanyId(companyId);
        List<TVehicleApplication> list = tVehicleApplicationService.selectTVehicleApplicationWithAllList(tVehicleApplication);
        PageInfo<TVehicleApplication> page = new PageInfo<>(list);
        return  success(new AppPage<>(page));
    }

    @ApiOperation("查看某个指定用车申请单")
    @GetMapping("/getVehicleApplyInfoByApplyId")
    public AjaxResult getVehicleApplyInfoByApplyId(@RequestParam Long applyId) {
        TVehicleApplication tVehicleApplication = tVehicleApplicationService.selectTVehicleApplicationByApplyId(applyId);
        return success(tVehicleApplication);
    }

    @ApiOperation("添加用车申请单")
    @PostMapping("/saveVehicleApply")
    public AjaxResult saveVehicleApply(@RequestBody TVehicleApplication param) {
        LoginUser loginUser = getLoginUser();
        param.setApplyTel(loginUser.getUser().getPhonenumber());
        param.setApplyName(loginUser.getUser().getNickName());
        param.setApplyId(SnowFlakeIDGenerator.getInstance().nextId());
        tVehicleApplicationService.save(param);
        return success();
    }

    @ApiOperation("修改用车申请单")
    @PostMapping("/updateVehicleApply")
    public AjaxResult updateVehicleApply(@RequestBody TVehicleApplication param) {
        //0：已申请，1：已审批，2已调度，3已接单，4已出车，5已还车，6撤销订单，7已驳回
        if (param.getOrderStatus() == 3 || param.getOrderStatus() == 4 || param.getOrderStatus() == 5){
            if (param.getOrderStatus() == 5) {
                //更新司机为空闲
                driverInfoService.updateDriverInfoByApplyId(param.getApplyId());
                //更新车辆状态为空闲
                vehicleManagementService.updateVehicleByApplyId(param.getApplyId());
            }
        }
        tVehicleApplicationService.saveOrUpdate(param);
        return success();
    }

    @ApiOperation("查看调度车辆")
    @GetMapping("/getDispatchVehiclesByApplyId")
    public AjaxResult getDispatchVehiclesByApplyId(@RequestParam Long applyId) {
        TDispatchVehicles tDispatchVehicles = new TDispatchVehicles();
        tDispatchVehicles.setApplyId(applyId);
        List<TDispatchVehicles> list = itDispatchVehiclesService.selectTDispatchVehiclesList(tDispatchVehicles);
        return success(list);
    }
    @ApiOperation("添加调度车辆")
    @PostMapping("/saveDispatchVehicles")
    public AjaxResult saveDispatchVehicles(@RequestBody List<TDispatchVehicles> param ) {

        for (TDispatchVehicles tDispatchVehicles : param) {
            //订单状态（2已调度，3已接单，4已出车，5已还车）
            tDispatchVehicles.setDispatchOrderStatus(2L);
            if (itDispatchVehiclesService.insertTDispatchVehicles(tDispatchVehicles) >0){
                TVehicleApplication tVehicleApplication =  new TVehicleApplication();
                tVehicleApplication.setApplyId(tDispatchVehicles.getApplyId());
                tVehicleApplication.setOrderStatus(2L);//2已调度
                tVehicleApplicationService.saveOrUpdate(tVehicleApplication);

                //更新车辆状态
                VehicleManagement vehicleManagement = new  VehicleManagement();
                vehicleManagement.setId(tDispatchVehicles.getVehicleId());
                vehicleManagement.setVehicleTaskStatus(1);//车辆状态0空闲1任务中
                vehicleManagementService.updateById(vehicleManagement);

                //更新司机状态
                DriverInfo driverInfo = new DriverInfo();
                driverInfo.setId(tDispatchVehicles.getDriverId());
                driverInfo.setDriverTaskStatus(1);//司机状态0空闲1任务中
                driverInfoService.updateById(driverInfo);
            }
        }
        return success();
    }
    @ApiOperation("调度转派")
    @PostMapping("/updateDispatchVehicles")
    public AjaxResult updateDispatchVehicles(@RequestBody List<TDispatchVehicles> param ) {
        for (TDispatchVehicles tDispatchVehicles : param) {
            itDispatchVehiclesService.updateTDispatchVehicles(tDispatchVehicles);
        }
        return success();
    }

    @ApiOperation("添加用车审批单")
    @PostMapping("/saveApprovalApply")
    public AjaxResult saveApprovalApply(@RequestBody TApprovalApply param) {
        LoginUser loginUser = getLoginUser();
        param.setCompanyId(loginUser.getUser().getDeptId());
        if( itApprovalApplyService.insertTApprovalApply(param) > 0){
            TVehicleApplication tVehicleApplication = new TVehicleApplication();
            tVehicleApplication.setApplyId(param.getApplyId());
            //审批状态（0:通过，1：不通过，2：待审批）
            if (param.getApprovealStatus() == 0) {
                tVehicleApplication.setOrderStatus(1L);//1：已审批
            }else if (param.getApprovealStatus() == 1){
                tVehicleApplication.setOrderStatus(7L);//7已驳回
            }
            tVehicleApplicationService.saveOrUpdate(tVehicleApplication);
        }
        return success();
    }

    @ApiOperation("查询用车审批单")
    @GetMapping("/getApprovalApplyByApplyId")
    public AjaxResult getApprovalApplyByApplyId(@RequestParam Long applyId) {
        TApprovalApply tApprovalApply = new TApprovalApply();
        tApprovalApply.setApplyId(applyId);
        List<TApprovalApply> list = itApprovalApplyService.selectTApprovalApplyList(tApprovalApply);
        return success(list);
    }

    @ApiOperation("驾驶员下拉列表")
    @GetMapping("/getDriverByCompanyId")
    public AjaxResult getDriverByCompanyId(@RequestParam(value = "companyId", required = false ) Long companyId,
                                           @RequestParam(value = "driverTaskStatus", required = false ) Integer driverTaskStatus,
                                           @RequestParam(value = "name", required = false ) String name,
                                           @RequestParam Integer pageNum, @RequestParam Integer pageSize) {
        LoginUser loginUser = getLoginUser();
        if (companyId == null){
            companyId = loginUser.getDeptId();
        }
        PageHelper.startPage(pageNum, pageSize);
        DriverInfo driverInfo = new DriverInfo();
        driverInfo.setCompanyId(companyId);
        driverInfo.setName(name);
        //司机状态0空闲1任务中
        driverInfo.setDriverTaskStatus(driverTaskStatus);

        List<DriverInfo> driverList = driverInfoService.selectList(driverInfo);
        driverList.stream().map(i -> new JSONObjectPro()
                .put("driverId", i.getId())
                .put("companyId", i.getCompanyId())
                .put("companyName", i.getCompanyName())
                .put("name", i.getName())
                .put("contactNumber", i.getContactNumber())
                .put("sex", i.getSex())
                .put("age", i.getAge())
                .put("driverTaskStatus", i.getDriverTaskStatus())
                .put("idCard", i.getIdCard())
                .put("driverPic", i.getPicture())
        ).collect(Collectors.toList());
        PageInfo<DriverInfo> page = new PageInfo<>(driverList);
        return success(new AppPage<>(page));
    }

    @ApiOperation("查询公司下的所有车辆")
    @GetMapping("/getVehicleSelectList")
    public AjaxResult getVehicleSelectList(@RequestParam(value = "companyId", required = false ) Long companyId,
                                           @RequestParam(value = "vehicleTaskStatus", required = false ) Integer vehicleTaskStatus,
                                           @RequestParam(value = "numberPlate", required = false ) String numberPlate,
                                           @RequestParam Integer pageNum, @RequestParam Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        VehicleManagement vehicleManagement = new VehicleManagement();
        LoginUser loginUser = getLoginUser();
        if (companyId == null){
            companyId = loginUser.getDeptId();
        }
        vehicleManagement.setCompanyId(companyId);
        //车辆状态0空闲1任务中
        vehicleManagement.setVehicleTaskStatus(vehicleTaskStatus);
        vehicleManagement.setNumberPlate(numberPlate);

        List<VehicleManagement> vehicleList = vehicleManagementService.selectList(vehicleManagement);
        vehicleList.stream().map(i -> new JSONObjectPro()
                .put("vehicleId", i.getId())
                .put("companyId", i.getCompanyId())
                .put("companyName", i.getCompanyName())
                .put("numberPlate", i.getNumberPlate())
                .put("vehicleColor", i.getVehicleColor())
                .put("vehicleTaskStatus", i.getVehicleTaskStatus())
                .put("vehicleModel", i.getVehicleModel())
                .put("vehiclePic", i.getVehiclePic())
        ).collect(Collectors.toList());
        PageInfo<VehicleManagement> page = new PageInfo<>(vehicleList);
        return success(new AppPage<>(page));
    }

    @ApiOperation("用车申请凭证")
    @PostMapping("/uploadVoucher")
    public AjaxResult uploadVoucher(@RequestBody MultipartFile[] file) {
        return success(uploadFile(file, "voucher"));
    }

    @ApiOperation("查询所有公司树列表")
    @GetMapping("/treeListWithParents")
    public AjaxResult treeListWithParents() {
        return success(deptService.treeListWithParents());
    }

}
